package com.leoman.filter;

import com.leoman.common.logger.Logger;
import com.leoman.core.Configue;
import com.leoman.core.Constant;
import com.leoman.utils.BeanUtil;
import com.leoman.utils.HttpUtil;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.util.http.URIUtil;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wangbin on 2015/8/4.
 */
public class WeixinFilter implements Filter {

    private static String[] SKIP_URLS = new String[]{};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("=======================进入init方法==============================");
        String urls = filterConfig.getInitParameter("skipUrls");
        if (StringUtils.isNotBlank(urls)) {
            String temp[] = urls.split(",");
            List<String> list = new ArrayList<String>();

            for (String skipUrl : temp) {
                if (StringUtils.isNotBlank(skipUrl)) {
                    skipUrl = "^" + skipUrl.replaceAll("\\*", ".*") + "$";
                    list.add(skipUrl);
                }
            }
            SKIP_URLS = list.toArray(SKIP_URLS);
        }
        System.out.println("=======================退出init方法==============================");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        System.out.println("=======================进入doFilter方法==============================");
        String url = null;
        try {
            url = httpRequest.getRequestURI().toString();
            String contextPath = httpRequest.getContextPath();
            String queryString = httpRequest.getQueryString();
            url = url.substring(contextPath.length());
            Logger.info(contextPath + ", " + url + "," + queryString);
            Logger.info("url:" + httpRequest.getRequestURL());

            if (SKIP_URLS != null) {
                for (String skipUrl : SKIP_URLS) {
                    Pattern pattern = Pattern.compile(skipUrl, Pattern.DOTALL);
                    Matcher matcher = pattern.matcher(url);
                    if (matcher.find()) {
                        chain.doFilter(request, response);
                        return;
                    }
                }
            }

            String type = request.getParameter("type");

            WxCpUser wxCpUser = (WxCpUser) httpRequest.getSession().getAttribute(Constant.SESSION_WEIXIN_WXUSER);
            if (null != wxCpUser) {
                System.out.println("wxCpUser的UserId:" + wxCpUser.getUserId());
            } else {
                WxCpService wxCpService = (WxCpService) BeanUtil.getBean("wxCpService");

                String fullUrl = HttpUtil.getFullUrl(httpRequest, Configue.getBaseDomain());

                System.out.println("fullUrl:" + fullUrl);

                String OAUTH_URL;

                System.out.println("*******************************************************************************************************");
                System.out.println("*******************************************************************************************************");
                System.out.println("type：" + type);
                System.out.println("*******************************************************************************************************");
                System.out.println("*******************************************************************************************************");

                // 1=协和齿环，2=泛洲中越，默认为泛洲中越
                if (StringUtils.isBlank(type) || type.equals("2")) {
                    OAUTH_URL = wxCpService.oauth2buildAuthorizationUrl(fullUrl, WxConsts.OAUTH2_SCOPE_BASE);

                    ((HttpServletRequest) request).getSession().setAttribute("userRequestType", "2");
                } else {
                    /*String oauth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
                    oauth_url = oauth_url + "appid=" + Constant.corpId2;
                    oauth_url = oauth_url + "&redirect_uri=" + URIUtil.encodeURIComponent(fullUrl);
                    oauth_url = oauth_url + "&response_type=code";
                    oauth_url = oauth_url + "&scope=snsapi_base";
                    oauth_url = oauth_url + "&state=" + WxConsts.OAUTH2_SCOPE_BASE;

                    OAUTH_URL = oauth_url + "#wechat_redirect";*/

                    wxCpService = (WxCpService) BeanUtil.getBean("wxCpService1");
                    OAUTH_URL = wxCpService.oauth2buildAuthorizationUrl(fullUrl, WxConsts.OAUTH2_SCOPE_BASE);

                    ((HttpServletRequest) request).getSession().setAttribute("userRequestType", "1");
                }

                System.out.println("domain:" + httpRequest.getSession().getAttributeNames());

                httpResponse.sendRedirect(OAUTH_URL);
                System.out.println("OAUTH_URL:" + OAUTH_URL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        chain.doFilter(request, response);
        System.out.println("=======================退出doFilter方法==============================");
    }

    @Override
    public void destroy() {

    }
}
